<!--
 * @Description: 
 * @Author: chenju
 * @Date: 2022-03-22 17:08:41
 * @LastEditors: qingyang
 * @LastEditTime: 2023-07-24 10:54:29
-->
<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    size="small"
  >
    <el-form ref="formRef" :model="taskForm" :rules="rules" label-position="top">
      <el-row>
        <el-col :span="24">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="taskForm.supplierName" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供应商编码" prop="supplierCode">
            <el-input v-model="taskForm.supplierCode" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供应商类型" prop="supplierType">
            <el-select v-model="taskForm.supplierType" placeholder="请选择">
              <el-option
                v-for="item in SupplierTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'AddOrEditSupplierDialog'
};
</script>
<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { useMessage } from '@/hooks/useMessage';
import { rules } from './rules';
import { ICreateSupplierParams } from '@/apis/system/config/model/supplierModel';
import { createSupplier, editSupplier, getSupplierDetail } from '@/apis/system/config/supplier';
import { SupplierTypeOptions } from '@/constants/enum';

interface SelectFillTypeDialogProps {
  visible: boolean;
  // 提交类型
  type: 'ADD' | 'EDIT';
  // 当前任务编号，编辑时必传
  supplierNo?: string;
}
const props = withDefaults(defineProps<SelectFillTypeDialogProps>(), {
  visible: false,
  type: 'ADD'
});
const emit = defineEmits(['update:visible', 'refresh']);

const { createMessage } = useMessage();

const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    if (!visible) {
      // 关闭时清空数据
      handleClear();
    } else {
      // 打开时初始化新数据
      initVisible();
    }
  }
);
const title = computed(() => {
  return props.type === 'EDIT' ? '编辑供应商' : '新增供应商';
});
const isEditTask = computed(() => {
  return !!(props.type === 'EDIT');
});
const formRef = ref();
const loading = ref(false);
const taskForm = reactive({
  supplierCode: '',
  supplierName: '',
  supplierType: ''
});

// 提交按钮
function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitTaskReq();
    }
  });
}

// 请求接口
async function submitTaskReq() {
  try {
    loading.value = true;
    const params: ICreateSupplierParams = {
      supplierCode: taskForm.supplierCode,
      supplierName: taskForm.supplierName,
      supplierType: taskForm.supplierType
    };
    if (isEditTask.value) {
      Object.assign(params, {
        supplierNo: props.supplierNo
      });
      await editSupplier(params);
    } else {
      await createSupplier(params);
    }
    createMessage.success(`${isEditTask.value ? '编辑' : '新增'}供应商成功`);
    dialogVisible.value = false;
    loading.value = false;
    emit('refresh');
  } catch (error) {
    loading.value = false;
  }
}

// 关闭时清空数据
function handleClear() {
  loading.value = false;
  formRef.value?.resetFields();
  taskForm.supplierCode = '';
  taskForm.supplierName = '';
  taskForm.supplierType = '';
}

// 打开时初始化
async function initVisible() {
  if (props.type === 'EDIT' && props.supplierNo) {
    try {
      const info = await getSupplierDetail(props.supplierNo);
      taskForm.supplierCode = info.supplierCode;
      taskForm.supplierName = info.supplierName;
      taskForm.supplierType = info.supplierType;
    } catch (error) {
      console.log('error', error);
    }
  } else {
    handleClear();
  }
}
</script>
